package com.yygo.webapp.controller;

/**
 * Created by tiansha on 2015/10/9.
 */

import com.yygo.Constants;
import com.yygo.model.BondCompany;
import com.yygo.model.LoanProduct;
import com.yygo.model.LoanRequest;
import com.yygo.model.User;
import com.yygo.service.BondManager;
import com.yygo.service.LoanProductManager;
import com.yygo.service.LoanRequestManager;
import com.yygo.service.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;


@Controller
@RequestMapping("/removeBondProducts")
public class RemoveBondProductsController {

    @Autowired
    private BondManager bondManager;
    @Autowired
    private LoanProductManager loanProductManager;

    @Autowired
    private UserManager userManager;

    @RequestMapping(method = RequestMethod.POST)
    public String batchExport(Model model, HttpServletRequest request, @RequestParam(required = true, value = "bondId") Long bondId, @RequestParam(required = true, value = "selectedIds") Long[] selectedIds, Principal principal) {
        User loginUser = userManager.getUserByUsername(principal.getName());
        if (!loginUser.hasRole(Constants.ADMIN_ROLE)) {
            throw new AccessDeniedException("You have no right to remove bond products");
        }

        BondCompany bondCompany = bondManager.loadBond(bondId);

        for (Long id : selectedIds) {
            LoanProduct loanProduct = loanProductManager.get(id);
            bondCompany.getLoanProducts().remove(loanProduct);
        }
        bondManager.save(bondCompany);

        return "redirect:/bondCompanyform?id="+bondId;
    }

}
